package cn.stylefeng.guns.workflow.controller;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ModelEntityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_DESCRIPTION;
import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_NAME;

/**
* @author: lujie
* @create: 2020/9/14
* @description: ModelerController 流程模型管理
**/
@Controller
@RequestMapping("/flowModel")
@Slf4j
public class ModelerController  extends BaseController {

    private static String PREFIX = "/modular/flowModel/";

    @Resource
    private RepositoryService repositoryService;


    /**
     * 跳转到流程模型列表页面
     * @return
     */
    @GetMapping
    public String index() {
        return PREFIX + "model.html";
    }


    /**
     * 跳转到流程模型添加页面
     * @return
     */
    @GetMapping("/toCreateModelHTML")
    public String toCreateModelHTML(){
        return  PREFIX+"createModel.html";
    }

    @GetMapping("/list")
    @ResponseBody
    public Object list(ModelEntityImpl modelEntity) {
        String modelKey = modelEntity.getKey();
        String modelName = modelEntity.getName();

        Page page = LayuiPageFactory.defaultPage();
        int current = (int) page.getCurrent();
        int size = (int) page.getSize();
        ModelQuery modelQuery = repositoryService.createModelQuery();
        if (StrUtil.isNotBlank(modelKey)){
            modelQuery.modelKey(modelKey);
        }
        if (StrUtil.isNotBlank(modelName)){
            modelQuery.modelNameLike("%"+modelName+"%");
        }
        List<Model> list = modelQuery
                .orderByCreateTime().desc()
                .orderByLastUpdateTime().desc()
                .listPage((current-1)*size,size);

        page.setRecords(list);
        page.setTotal(modelQuery.count());
        page.setSize(size );
        page.setCurrent(current);
        return LayuiPageFactory.createPageInfo(page);
    }


    @RequestMapping("/deployFlowModel/{modelId}")
    @ResponseBody
    public  ResponseData  deployFlowModel(@PathVariable String modelId) throws  Exception{
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
            log.info("部署成功，部署ID=" + deployment.getId());
            return ResponseData.success("部署成功");
    }

    /**
     * 创建模型
     */
    @RequestMapping(value = "/create")
    @ResponseBody
    public ResponseData create(@RequestParam("name") String name, @RequestParam("key") String key,
                               @RequestParam(value = "description", required = false) String description) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(MODEL_DESCRIPTION, description);

            Model newModel = repositoryService.newModel();
            newModel.setMetaInfo(modelObjectNode.toString());
            newModel.setName(name);
            newModel.setKey(StringUtils.defaultString(key));

            repositoryService.saveModel(newModel);
            repositoryService.addModelEditorSource(newModel.getId(), editorNode.toString().getBytes("utf-8"));

            return  ResponseData.success(newModel.getId() );
        } catch (Exception e) {
            log.error("创建模型失败");
        }
        return ResponseData.error("创建模型失败");
    }

    /**
     * 删除模型
     * @param modelId
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData deleteById(String modelId){
        repositoryService.deleteModel(modelId);
        return SUCCESS_TIP;
    }

}
